package com.woman.beautylive.presentation.ui.main.setting;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.google.gson.Gson;
import com.woman.beautylive.BeautyLiveApplication;
import com.woman.beautylive.BuildConfig;
import com.woman.beautylive.R;
import com.woman.beautylive.data.bean.UpDataBean;
import com.woman.beautylive.domain.LocalDataManager;
import com.woman.beautylive.presentation.ui.base.BaseActivity;
import com.woman.beautylive.presentation.ui.chatting.utils.FileHelper;
import com.woman.beautylive.presentation.ui.chatting.utils.SharePreferenceManager;
import com.woman.beautylive.presentation.ui.login.LoginSelectActivity;
import com.woman.beautylive.presentation.ui.main.webview.SimpleWebViewActivity;
import com.woman.beautylive.presentation.ui.widget.MessageDialog;
import com.woman.beautylive.util.Const;
import com.woman.beautylive.util.DataCleanManager;
import com.woman.beautylive.util.DownLoadUtil;
import com.woman.beautylive.util.L;
import com.woman.beautylive.util.Packages;
import com.umeng.analytics.MobclickAgent;
import com.yolanda.nohttp.Headers;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.model.UserInfo;
import rx.functions.Action1;

/**
 * @author Muyangmin
 * @since 1.0.0
 * 设置
 */
public class SettingActivity extends BaseActivity {

    public static Intent createIntent(Context context){
        return new Intent(context, SettingActivity.class);
    }

    private TextView tvAbout;
    private TextView tvVersion;
    private TextView tvCacheSize;
    private TextView tvUpVersion;
    private ProgressBar prgClearCache;
    private TextView tvOutLogin;
    private String myPlayPath;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void findViews(Bundle savedInstanceState) {
        subscribeFeatureStub(R.id.setting_rl_account);
        subscribeFeatureStub(R.id.setting_rl_black_list);
//        subscribeFeatureStub(R.id.setting_rl_clear_cache);
        subscribeFeatureStub(R.id.setting_rl_push_manage);

        tvAbout = $(R.id.setting_tv_about);
        tvVersion = $(R.id.setting_tv_version);
        tvUpVersion= (TextView) findViewById(R.id.setting_tv_upversion);
        tvCacheSize = $(R.id.setting_tv_cache_size);
        prgClearCache = $(R.id.setting_prg_clear_cache);
        tvOutLogin=$(R.id.setting_tv_logout);
        subscribeClick(R.id.setting_rl_feedback, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                startActivity(SimpleWebViewActivity.createIntent(SettingActivity.this,
                        getString(R.string.setting_feedback_url)));
            }
        });
        subscribeClick(R.id.setting_rl_about, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                startActivity(SimpleWebViewActivity.createIntent(SettingActivity.this,
                        getString(R.string.setting_about_url)));
            }
        });
        subscribeClick(R.id.setting_rl_black_list, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                Intent i=new Intent(SettingActivity.this,BlacklistActivity.class);
                startActivity(i);
            }
        });
        subscribeClick(R.id.setting_rl_upversion, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
//                更新
                toastShort("暂时没有提供更新下载地址呢");
//                upData();
            }
        });

//        我的直播地址
        subscribeClick(R.id.setting_my_pullpath, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                showDialog();
            }
        });

        subscribeClick(R.id.setting_tv_logout, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {

                UserInfo info = JMessageClient.getMyInfo();
                if (null != info) {
                    File file = info.getAvatarFile();
                    if (file != null && file.isFile()) {
                    } else {
                        String path = FileHelper.getUserAvatarPath(info.getUserName());
                        file = new File(path);
                        if (file.exists()) {
                        }
                    }
                    SharePreferenceManager.setCachedUsername(info.getUserName());
                    SharePreferenceManager.setCachedAvatarPath(file.getAbsolutePath());
                    JMessageClient.logout();
                    L.e("lw", "退出登录");
                }

                startActivity(LoginSelectActivity.createIntent(SettingActivity.this));
                (SettingActivity.this).sendFinishBroadcast(LoginSelectActivity
                        .class.getSimpleName());
            }
        });
//        得到自己的直播地址
        getMyPath();
    }

    @Override
    protected void onResume() {
        MobclickAgent.onPageStart("设置");
        super.onResume();
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPageEnd("设置");
        super.onPause();
    }

    @Override
    protected void init() {
        tvAbout.setText(getString(R.string.setting_about, getString(R.string.app_name)));
        tvVersion.setText(getString(R.string.setting_version, Packages.getVersionName(this)));
        tvUpVersion.setText(getString(R.string.setting_up_version));
        //Color egg
        tvVersion.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(SettingActivity.this,
                        String.format("Flavor : %1$s\nBuildType : %2$s\nVersionCode : %3$s",
                                BuildConfig.FLAVOR,
                                BuildConfig.BUILD_TYPE,
                                BuildConfig.VERSION_CODE),
                        Toast.LENGTH_LONG).show();
                return false;
            }
        });

        String size;
        try{
            size = DataCleanManager.getTotalCacheSize(this);
            subscribeClick(R.id.setting_rl_clear_cache, new Action1<Void>() {
                @Override
                public void call(Void aVoid) {
                    tvCacheSize.setVisibility(View.INVISIBLE);
                    prgClearCache.setVisibility(View.VISIBLE);
                    try{
                        Fresco.getImagePipeline().clearCaches();
                        DataCleanManager.clearAllCache(SettingActivity.this);
                    }catch (Exception e){
                        L.w(LOG_TAG, "Error while clearing cache!", e);
                    }
                    tvCacheSize.setText(R.string.setting_cache_empty);
                    tvCacheSize.setVisibility(View.VISIBLE);
                    prgClearCache.setVisibility(View.INVISIBLE);
                }
            });
        }catch (Exception e){
            size = getString(R.string.setting_cache_empty);
        }
        tvCacheSize.setText(size);
    }

    private int PAGER_JSON=1;
    public void upData(){
//      域名 139.129.19.190
        Request<JSONObject> request = NoHttp.createJsonObjectRequest("http://www.cxzfb.cn/test.php", RequestMethod.GET);
        BeautyLiveApplication.getRequestQueue().add(PAGER_JSON, request, upDataOnResponse);
    }

    private OnResponseListener<JSONObject> upDataOnResponse = new OnResponseListener<JSONObject>() {
        @Override
        public void onStart(int i) {
            L.i("lll", "开始了");
        }

        @Override
        public void onSucceed(int i, Response<JSONObject> response) {
            if (i == PAGER_JSON) {// 判断what是否是刚才指定的请求
                //                {"code":0,"msg":"ok","data":"320200"}这个是什么
                // 请求成功
                JSONObject result = response.get();// 响应结果
                Log.i("mrl",result.toString()+" ");
                Gson gson=new Gson();
                UpDataBean upDataBean=gson.fromJson(result.toString(),UpDataBean.class);
                isUpData(upDataBean);
                // 响应头
                Headers headers = response.getHeaders();
                headers.getResponseCode();// 响应码
                response.getNetworkMillis();// 请求花费的时间
            }
        }

        @Override
        public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
            L.i("lll", "请求失败了哦" + s);
        }

        @Override
        public void onFinish(int i) {
            L.i("lll", "viewpager结束了");
        }
    };
    //  判断是否更新
    public void isUpData(UpDataBean updata){
        if (upDataState(Packages.getVersionName(this),updata.getVersion())<0){
            showUpDataDialog(updata);
        }else {
            toastShort("已是最新版本啦");
        }
    }

    public void showUpDataDialog(final UpDataBean updata){
        MessageDialog dialog = new MessageDialog(this);
        dialog.setContent(R.string.mian_updata_tip);
        dialog.setMessageDialogListener(new MessageDialog.MessageDialogListener() {
            @Override
            public void onCancelClick(MessageDialog dialog) {
                dialog.dismiss();
            }

            @Override
            public void onCommitClick(MessageDialog dialog) {
                if (dialog!=null && dialog.isShowing()){
                    dialog.dismiss();
                }
//                进行下载
                downLoadApk(updata);
            }
        });
        dialog.show();
    }


    /*
	 * 从服务器中下载APK
	 */
    protected void downLoadApk(final UpDataBean updata) {
        final ProgressDialog pd;    //进度条对话框
        pd = new  ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.show();
        new Thread(){
            @Override
            public void run() {
                try {
                    File file = DownLoadUtil.getFileFromServer(updata.getUrl(),pd);
                    sleep(3000);
                    installApk(file);
                    pd.dismiss(); //结束掉进度条对话框
                } catch (Exception e) {
                    handler.sendEmptyMessage(5);
                    e.printStackTrace();
                }
            }}.start();
    }

    //安装apk
    protected void installApk(File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }

    Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//             *  开启直播验证
//             *
//             *  @param reponse  token  ucid
//             *
//             *  @return 服务器返回 data:( 0 ：可直播；1：未签约；2：时间不对;3:其他错误)
            switch (msg.what){
                case 5:
                    toastShort("下载失败");
                    break;
            }
        }
    };

    public int upDataState(String oldVersion,String newVersion){
//        old大于new则不进行更新  负数更新
        return oldVersion.compareTo(newVersion);
    }

    /**
     * 这是兼容的 AlertDialog
     */
    private void showDialog() {
  /*
  这里使用了 android.support.v7.app.AlertDialog.Builder
  可以直接在头部写 import android.support.v7.app.AlertDialog
  那么下面就可以写成 AlertDialog.Builder
  */
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setTitle("是否复制我的直播地址");
        builder.setMessage(myPlayPath);
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager)SettingActivity.this.getSystemService(Context.CLIPBOARD_SERVICE);
                clipboardManager.setText(myPlayPath);
                toastShort("复制成功");
            }
        });
        builder.show();
    }

    public void getMyPath(){
//      域名 139.129.19.190
        Request<JSONObject> request = NoHttp.createJsonObjectRequest(Const.WEB_BASE_URL+"qiniu/getPullAddress", RequestMethod.GET);
        request.add("token",LocalDataManager.getInstance().getLoginInfo().getToken());
        request.add("roomID",LocalDataManager.getInstance().getLoginInfo().getCurrentRoomNum());
        BeautyLiveApplication.getRequestQueue().add(PAGER_JSON, request, upMyPathResponse);
    }

    private OnResponseListener<JSONObject> upMyPathResponse = new OnResponseListener<JSONObject>() {
        @Override
        public void onStart(int i) {
            L.i("lll", "开始了");
        }

        @Override
        public void onSucceed(int i, Response<JSONObject> response) {
            if (i == PAGER_JSON) {// 判断what是否是刚才指定的请求
                //                {"code":0,"msg":"ok","data":"320200"}这个是什么
                // 请求成功
                JSONObject result = response.get();// 响应结果
                try {
                    myPlayPath=result.getString("data");
                    Log.i("mrl",result.toString()+" "+result.getString("data"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // 响应头
                Headers headers = response.getHeaders();
                headers.getResponseCode();// 响应码
                response.getNetworkMillis();// 请求花费的时间
            }
        }

        @Override
        public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
            L.i("lll", "请求失败了哦" + s);
        }

        @Override
        public void onFinish(int i) {
            L.i("lll", "viewpager结束了");
        }
    };

}
